package com.hnjd.headline.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnjd.headline.mapper.UserMapper;
import com.hnjd.headline.pojo.User;
import com.hnjd.headline.utils.CryptoFactory;
import com.hnjd.headline.utils.TokenHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.hnjd.headline.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 服务接口实现
 *
 * @author kancy
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2025-06-16 15:53:03
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private final UserMapper userMapper;

    @Autowired
    private final CryptoFactory cryptoFactory;

    @Autowired
    private final TokenHelper tokenHelper;

    @Override
    public String login(User user) {

        // 根据用户名查询数据
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User storeUser = userMapper.selectOne(queryWrapper);

        // 判空
        if (storeUser == null) {
            // 用户名不存在  返回空对象
            return null;
        }

        // 判密码
        if (cryptoFactory.encrypt(user.getUserPwd()).equals(storeUser.getUserPwd())) {
            // 正确  生成token
            return tokenHelper.createToken(storeUser.getUid().longValue());
        } else {
            // 错误  返回空字符串
            return "";
        }
    }

    @Override
    public User getUserByToken(String token) {
        // 校验token有效性
        if (tokenHelper.isExpiration(token)) {
            return null;
        }

        // 从token中解析用户id
        Long userId = tokenHelper.getUserId(token);
        // 根据用户id查询用户信息
        return userMapper.selectById(userId);
    }

    @Override
    public Boolean checkUserNameUsed(String username) {
        // 根据用户名查询数据
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User storeUser = userMapper.selectOne(queryWrapper);

        // 判空
        // 用户名已存在  返回true
        // 用户名不存在  返回false
        return storeUser != null;
    }

    @Override
    public int register(User user) {
        // 对密码进行加密
        String encryptPassword = cryptoFactory.encrypt(user.getUserPwd());
        user.setUserPwd(encryptPassword);
        // 保存用户信息
        return userMapper.insert(user);
    }

    @Override
    public Boolean checkTokenExpiration(String token) {
        // 校验token是否过期
        return tokenHelper.isExpiration(token);
    }
    
}